package coolapk.cj.cj.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import coolapk.cj.cj.dto.PersonDto;
import coolapk.cj.cj.entity.Person;
import coolapk.cj.cj.service.PersonService;
import coolapk.cj.cj.utils.BindingResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author wenjunjun9
 * @created 2021-02-16 18:54
 * @description
 */
@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping("/addRecord")
    public ResponseEntity<String> addRecords(@RequestBody @Valid PersonDto personDto, BindingResult bindingResult) {
        try {
            BindingResultUtil.apply(bindingResult);

            personService.addRecord(personDto);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

    @PostMapping("/page")
    public ResponseEntity<IPage<Person>> page(@RequestBody Page<Person> page) {
        IPage<Person> result = personService.pageQuery(page);
        return ResponseEntity.ok(result);
    }
}
